package mailsystem.persistance;

import java.util.List;

import mailsystem.Mailbox;
import mailsystem.Message;
import mailsystem.persistance.database.ContactDB;
import mailsystem.persistance.database.KeptMessageDB;
import mailsystem.persistance.database.MailBoxDB;
import mailsystem.persistance.database.NewMessageDB;

public class MailsystemPersistance {
	public static final int DBMODE = 1;
	public static final int DBMODE_TEST = 2;
	private MailBoxPersistance mailboxes;
	private ContactPersistance contacts;
	private NewMessagePersistance newMessages;
	private KeptMessagePersistance keptMessages;
	private int mailboxCount;
	
	public MailsystemPersistance(int mode, int theMailboxCount)
	{
		if ( mode == DBMODE )
		{
			mailboxes = new MailBoxDB(this);
			contacts = new ContactDB(this);
			newMessages = new NewMessageDB(this);
			keptMessages = new KeptMessageDB(this);
		}
		else if ( mode == DBMODE_TEST)
		{
			mailboxes = new MailBoxDB(this);
			contacts = new ContactDB(this);
			newMessages = new NewMessageDB(this);
			keptMessages = new KeptMessageDB(this);
			((MailBoxDB)mailboxes).changeToTestMode();
			((ContactDB)contacts).changeToTestMode();
			((NewMessageDB)newMessages).changeToTestMode();
			((KeptMessageDB)keptMessages).changeToTestMode();
		}
		else
			throw new IllegalArgumentException("Unknow mode");
		mailboxCount = theMailboxCount;
		
		if ( mailboxes.listAll().size() == 0 )
		{
			createNewMailBoxes();
		}
	}
	
	public void addMailbox(Mailbox box)
	{
		mailboxes.add(box);
	}
	
	public void deleteMailbox(Mailbox box)
	{
		mailboxes.delete(box);
	}
	
	public void updateMailbox(Mailbox box)
	{
		mailboxes.update(box);
	}
	
	public List<Mailbox> listAllMailbox()
	{
		return mailboxes.listAll();
	}
	
	public void addContact(Mailbox box, Mailbox contact)
	{
		contacts.add(box, contact);
	}
	
	public void deleteContact(Mailbox box, Mailbox contact)
	{
		contacts.delete(box, contact);
	}
	
	public List<Mailbox> getAllContacts(Mailbox box)
	{
		return contacts.listAll(box);
	}
	
	public void addNewMessage(Mailbox box, Message message)
	{
		newMessages.add(box, message);
	}
	
	public void deleteNewMessage(Message message)
	{
		newMessages.delete(message);
	}
	
	public List<Message> listAllNewMessages(Mailbox box)
	{
		return newMessages.listAll(box);
	}
	
	public void addKeptMessage(Mailbox box, Message message)
	{
		keptMessages.add(box, message);
	}
	
	public void deleteKeptMessage(Message message)
	{
		keptMessages.delete(message);
	}
	
	public List<Message> listAllKeptMessages(Mailbox box)
	{
		return keptMessages.listAll(box);
	}	
	
	private void createNewMailBoxes()
	{
		for (int i = 0; i < mailboxCount; i++) {
			String passcode = "" + (i + 1);
			String name = "Mailbox " + (i + 1);
			String greeting = "You have reached mailbox " + (i + 1)
					+ ". \nPlease leave a message now.";
			Mailbox mailbox = new Mailbox(i, passcode, greeting, name, null);
			mailboxes.add(mailbox);
		}
	}
}
